package com.gxd.dao.impl;

import com.gxd.dao.UserDao;
import com.gxd.domain.User;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
    @Override
    public long selectByName(String username) {
        try {
            String sql=" select count(0) from tb_user where username=? ";
            long count = (long)queryRunner.query(sql, new ScalarHandler(), username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int insert(User user) {
        try {
            String sql=" insert into tb_user value(null,?,md5(?),?,?,?,?,?) ";
            Object[] params={user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
            int i = queryRunner.update(sql, params);
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where username=? and password= md5(?) ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(User.class),username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public User findAll(int uid) {
        String sql=" select id,username,password,email,gender,flag,role,code from tb_user where id=?  ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(User.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
